const countTotalPageCount = (totalCount, pageSize) => {
  if (totalCount % pageSize ===0) {
    return parseInt(totalCount / pageSize);
  } else {
    return parseInt(totalCount / pageSize) + 1;
  }
};

module.exports = {

	getUserId() {
		const user = this.request.user;
		return user.userId;
	},
	getUser() {
		const user = this.request.user;
		return user;
	},
	getQuery(key) {
		const query = this.request.query;
		if (query && query[key]) {
			return query[key];
		}
		return '';
	},

	apiPageList(pageList, totalCount) {
		const query = this.request.query;

		const {
      pageNum = 1,
      pageSize = 10,
		} = query;

		this.body = {
			success: true,
			pageList,
			page: {
				totalCount,
				pageNum: Number(pageNum),
				pageSize: Number(pageSize),
				pageCount: countTotalPageCount(totalCount, Number(pageSize)),
			},
		};
    this.status = 200;
	},

	getPageListOption() {
		const query = this.request.query;
		const {
      pageNum = 1,
      pageSize = 10,
		} = query;

		const pageInfo = {
      pageNum: Number(pageNum),
      pageSize: Number(pageSize),
		};

		const option = {
      skip: (pageInfo.pageNum - 1) * pageInfo.pageSize,
      limit: pageInfo.pageSize || 10,
		};

		return [ option ];
	},

	getPageInfo() {
		const query = this.request.query;
		const {
      pageNum = 1,
      pageSize = 10,
		} = query;
		
		const pageInfo = {
      pageNum: Number(pageNum),
      pageSize: Number(pageSize),
		};
		return [ pageInfo.pageNum, pageInfo.pageSize ];
	},

  // 生成token
	getToken(value) {
		return this.app.jwt.sign(value, this.app.config.jwt.secret);
  },

  // 验证方法
	async checkToken(token, ws = false){
		let user = this.app.jwt.verify(token, this.app.config.jwt.secret)
		if (ws){
		   if(!user || (token != await this.service.cache.get('user_'+user.id))) {
			return false
		  } 
		}
		
		return user
	},

	// 用户上线
	async online(userId) {
		const { service, app } = this;
		
		let pid = process.pid;

		let [ opid ] = await service.mongoCache.get(`online_${userId}`);
		if (opid && pid !== opid) {
			// 这里是异步操作,会把if后面代码先执行
			console.log('offline');
			app.messenger.sendTo(opid, "offline", userId);
		}
		
		setTimeout(async () => {
			app.ws.user[userId] = this.websocket;
			await service.mongoCache.set(`online_${userId}`, pid);
			console.log('ctx_online在线人数==================', Object.keys(app.ws.user).length);
			this.websocket.send(JSON.stringify({ msg:'connOk' }));
		}, 300);
	}

}